﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mahanet.Abyss.PathCalculation;

namespace motion.Calibrators
{
	public class AimerCalibrator
	{
		#region Fields

		private Coordinate3DAimer m_Aimer;

		#endregion

		#region C'tor

		public AimerCalibrator(Coordinate3DAimer aimer)
		{
			m_Aimer = aimer;
		}

		#endregion

		#region Public Methods

		public void CalibrateMovement(Coordinate3D zeroAnglePoint,
									  Coordinate3D horizontalMovementPoint1,
									  Coordinate3D horizontalMovementPoint2,
									  Coordinate3D verticalMovementPoint1,
									  Coordinate3D verticalMovementPoint2)
		{
			// TODO: reduce error by finding the gun rotation center as the closest interesection point of the three lines (with a second zeroLocationPoint)
			// otherwise, we could estimate the error by comparing with the other intersections
			Line3D horizontalMovementLine = new Line3D(horizontalMovementPoint1, horizontalMovementPoint2);
			Line3D verticalMovementLine = new Line3D(verticalMovementPoint1, verticalMovementPoint2);
      m_Aimer.GunRotationCenter = new Coordinate3D(0, 0, 0);// horizontalMovementLine.GetMinimalEquidistantPoint(verticalMovementLine);

			// TODO: reduce error by using 4 points to find the plane using a second zeroLocationPoint
			m_Aimer.GunHorizontalZeroAngleDirection = new Plane3D(zeroAnglePoint, horizontalMovementPoint1, horizontalMovementPoint2);
			m_Aimer.GunVerticalZeroAngleDirection = new Plane3D(zeroAnglePoint, verticalMovementPoint1, verticalMovementPoint2);
		}
		
		// Supplying a higher value than the actual value is safer - it makes the aimer not wait for more data when the target
		// is close to the danger zone.
		public void CalibrateTiming(double dataGenerationInterval)
		{
			m_Aimer.MaximalDataSeriesIntervalInTicks = dataGenerationInterval;
		}

		// Returns the danger zone's fourth point for displya
		public Coordinate3D CalibrateDangerZone(Coordinate3D dangerZoneBottomLeftEdge,
										Coordinate3D dangerZoneTopLeftEdge,
										Coordinate3D dangerZoneBottomRightEdge)
		{
			// TODO: reduce error by receiving the fourth corner as well and finding the closest plane to the 4 points
			Vector3D widthVector = dangerZoneBottomRightEdge - dangerZoneBottomLeftEdge;
			Vector3D heightVector = dangerZoneTopLeftEdge - dangerZoneBottomLeftEdge;

			m_Aimer.DangerZone = new Rectangle3D(dangerZoneBottomLeftEdge, widthVector, heightVector);

			return m_Aimer.DangerZone.TopRightCorner;
		}

		#endregion
	}
}
